<?php
//--------------------------------------------------
//	Filename: function_blog.php
//--------------------------------------------------
// Information:
// All the blog-function is listed here. 
//--------------------------------------------------
if(!defined('IN_INDEX'))
{
	printError("ACCESS DENIED", "This page is hidden.");
	exit;
}

// Exercise
$EXERCISE_LIST = exercise_list();
$POUNDS_PER_KG = 2.20462262;

function kg_to_pounds($input)
{
	global $POUNDS_PER_KG;
	return (float)((float)$input * $POUNDS_PER_KG);
}

function pounds_to_kg($input)
{
	global $POUNDS_PER_KG;
	return (float)((float)$input / $POUNDS_PER_KG);
}

if(checkSession())
{
	if($USER->getWeight_metric() == 'lbs')
	{
		$w_metric = 'lbs';
		$w_metric_long = 'pounds';
		function calcToKg($input) // Convert from lbs to kg
		{
			global $POUNDS_PER_KG;
			return (float)((float)$input / $POUNDS_PER_KG);
		}
		
		function calcFromKg($input) // Convert from kg to lbs
		{
			global $POUNDS_PER_KG;
			return (float)((float)$input * $POUNDS_PER_KG);
		}
		
		function r_nr($input) // Rounds to nearest 2.5kg
		{
			return round($input/2.5)*2.5;
		}
		
		function r_nr2($input) // Dont round but only show 2 decimals, used for bodyweight
		{
			return round($input, 2);
		}
	}
	else
	{
		$w_metric = 'kg';
		$w_metric_long = 'kilo';
		
		function calcToKg($input)
		{
			return (float)$input;
		}
		
		function calcFromKg($input)
		{
			return (float)$input;
		}
		
		function r_nr($input)
		{
			return round($input/2.5)*2.5;
		}
		
		function r_nr2($input) // Dont round but only show 2 decimals, used for bodyweight
		{
			return round($input, 2);
		}
	}
}
else
{
	$w_metric = 'kg';
	$w_metric_long = 'kilo';
		
	function calcToKg($input)
	{
		return (float)$input;
	}
		
	function calcFromKg($input)
	{
		return (float)$input;
	}
		
	function r_nr($input)
	{
		return round($input, 2);
	}
}

// Calculate wilks point from bodyweight, sex and weight lifted
function wilks($bodyweight,$sex,$weightlifted)
{
 if ($sex == "male")
 {
	 $a = -216.0475144;
	 $b = 16.2606339;
	 $c = -0.002388645;
	 $d = -0.00113732;
	 $e = 7.01863E-06;
	 $f = -1.291E-08;
 } 
 else
 {
	 $a = 594.31747775582;
	 $b = -27.23842536447;
	 $c = 0.82112226871;
	 $d = -0.00930733913;
	 $e = 0.00004731582;
	 $f = -0.00000009054;
 }
 $wilks = 500/($a + $b*$bodyweight + $c*pow($bodyweight,2) + $d*pow($bodyweight,3) + $e*pow($bodyweight,4) + $f*pow($bodyweight,5));
 $wilkscoef = number_format($wilks, 4);
 $wilkspoints = $wilkscoef*$weightlifted;
 
 return $wilkspoints;
}

// Calculate sinclair point from bodyweight, sex and weight lifted
function sinclair($bodyweight,$sex,$weightlifted)
{

 if ($sex == "male")
 {
	 $a = 0.784780654;
	 $b = 173.961;
 } 
 else
 {
	 $a = 1.056683941;
	 $b = 125.441;
 }
 
 // X log(10)(Bodyweight/B)
 $x1 = log($bodyweight/$b,10);
 
 // AX^2
 $x2 = $a*($x1*$x1);
 
 
 // S.C. = 10^(AX^(2))
 $sinclair = pow(10, $x2);
 
 // Weightlifted * Sinclair
 $sinclairpoints = $weightlifted*$sinclair;
 
 return round($sinclairpoints, 2);
}

function bestsquat($tid)
{
	global $db;
	
	//Best squat
	$sql = "SELECT max(kg) as kg FROM " . LIFT_TABLE . " WHERE exercise_id='150' AND rep=1 AND training_id = '" . $tid . "' OR exercise_id='100' AND rep=1 AND training_id = '" . $tid . "' OR exercise_id='101' AND rep=1 AND training_id = '" . $tid . "' OR exercise_id='102' AND rep=1 AND training_id = '" . $tid . "' OR exercise_id='121' AND rep=1 AND training_id = '" . $tid . "' OR exercise_id='65' AND rep=1 AND training_id = '" . $tid . "' OR exercise_id='35' AND rep=1 AND training_id = '" . $tid . "' OR exercise_id='36' AND rep=1 AND training_id = '" . $tid . "' OR exercise_id='110' AND rep=1 AND training_id = '" . $tid . "' OR exercise_id='115' AND rep=1 AND training_id = '" . $tid . "' OR exercise_id='116' AND rep=1 AND training_id = '" . $tid . "' OR exercise_id='62' AND rep=1 AND training_id = '" . $tid . "' OR exercise_id='137' AND rep=1 AND training_id = '" . $tid . "' OR exercise_id='1'  AND rep=1 AND training_id = '" . $tid . "' OR exercise_id='134' AND rep=1 AND training_id = '" . $tid . "' OR exercise_id='33' AND rep=1 AND training_id = '" . $tid . "' OR exercise_id='5' AND rep=1 AND training_id = '" . $tid . "' OR exercise_id='7' AND rep=1 AND training_id = '" . $tid . "' OR exercise_id='184' AND rep=1 AND training_id = '" . $tid . "' LIMIT 1";
	if(!$result = $db->sql_query($sql))
	{
		printError("SQL ERROR", mysql_error($sql));
	}
	$row = mysql_fetch_array($result);
	return $row['kg'];
}

function bestbench($tid)
{
	global $db;
	
	//Best bench
	$sql2 = "SELECT max(kg) as kg FROM " . LIFT_TABLE . " WHERE exercise_id='133' AND rep=1 AND training_id = '" . $tid . "' OR exercise_id='132' AND rep=1 AND training_id = '" . $tid . "' OR exercise_id='131' AND rep=1 AND training_id = '" . $tid . "' OR exercise_id='130' AND rep=1 AND training_id = '" . $tid . "' OR exercise_id='129' AND rep=1 AND training_id = '" . $tid . "' OR exercise_id='128' AND rep=1 AND training_id = '" . $tid . "' OR exercise_id='127' AND rep=1 AND training_id = '" . $tid . "' OR exercise_id='125' AND rep=1 AND training_id = '" . $tid . "' OR exercise_id='124' AND rep=1 AND training_id = '" . $tid . "' OR exercise_id='119' AND rep=1 AND training_id = '" . $tid . "' OR exercise_id='88' AND rep=1 AND training_id = '" . $tid . "' OR exercise_id='104' AND rep=1 AND training_id = '" . $tid . "' OR exercise_id='113' AND rep=1 AND training_id = '" . $tid . "' OR exercise_id='143' AND rep=1 AND training_id = '" . $tid . "' OR exercise_id='38' AND rep=1 AND training_id = '" . $tid . "' OR exercise_id='26' AND rep=1 AND training_id = '" . $tid . "' OR exercise_id='27' AND rep=1 AND training_id = '" . $tid . "' OR exercise_id='89' AND rep=1 AND training_id = '" . $tid . "' OR exercise_id='114' AND rep=1 AND training_id = '" . $tid . "' OR exercise_id='29' AND rep=1 AND training_id = '" . $tid . "' OR exercise_id='152' AND rep=1 AND training_id = '" . $tid . "' OR exercise_id='32' AND rep=1 AND training_id = '" . $tid . "' OR exercise_id='34' AND rep=1 AND training_id = '" . $tid . "' OR exercise_id='19' AND rep=1 AND training_id = '" . $tid . "' OR exercise_id='6' AND rep=1 AND training_id = '" . $tid . "' OR exercise_id='37' AND rep=1 AND training_id = '" . $tid . "' OR exercise_id='2' AND rep=1 AND training_id = '" . $tid . "' OR exercise_id='180' AND rep=1 AND training_id = '" . $tid . "' OR exercise_id='179' AND rep=1 AND training_id = '" . $tid . "' OR exercise_id='181' AND rep=1 AND training_id = '" . $tid . "' OR exercise_id='190' AND rep=1 AND training_id = '" . $tid . "' LIMIT 1";
	if(!$result2 = $db->sql_query($sql2))
	{
		printError("SQL ERROR", mysql_error($sql2));
	}
	$row2 = mysql_fetch_array($result2);
	return $row2['kg'];
}
function bestdeadlift($tid)
{
	global $db;
	//Best deadlift
	$sql3 = "SELECT max(kg) as kg FROM " . LIFT_TABLE . " WHERE exercise_id='106' AND rep=1 AND training_id = '" . $tid . "' OR exercise_id='158' AND rep=1 AND training_id = '" . $tid . "' OR exercise_id='117' AND rep=1 AND training_id = '" . $tid . "' OR exercise_id='112' AND rep=1 AND training_id = '" . $tid . "' OR exercise_id='44' AND rep=1 AND training_id = '" . $tid . "' OR exercise_id='107' AND rep=1 AND training_id = '" . $tid . "' OR exercise_id='120' AND rep=1 AND training_id = '" . $tid . "' OR exercise_id='122' AND rep=1 AND training_id = '" . $tid . "' OR exercise_id='144' AND rep=1 AND training_id = '" . $tid . "' OR exercise_id='147' AND rep=1 AND training_id = '" . $tid . "' OR exercise_id='146' AND rep=1 AND training_id = '" . $tid . "' OR exercise_id='135' AND rep=1 AND training_id = '" . $tid . "' OR exercise_id='153' AND rep=1 AND training_id = '" . $tid . "' OR exercise_id='136' AND rep=1 AND training_id = '" . $tid . "' OR exercise_id='126' AND rep=1 AND training_id = '" . $tid . "' OR exercise_id='145' AND rep=1 AND training_id = '" . $tid . "' OR exercise_id='123' AND rep=1 AND training_id = '" . $tid . "' OR exercise_id='118' AND rep=1 AND training_id = '" . $tid . "' OR exercise_id='41' AND rep=1 AND training_id = '" . $tid . "' OR exercise_id='3' AND rep=1 AND training_id = '" . $tid . "' AND rep=1 AND training_id = '" . $tid . "' OR exercise_id='8' AND rep=1 AND training_id = '" . $tid . "' OR exercise_id='39' AND rep=1 AND training_id = '" . $tid . "' OR exercise_id='40' AND rep=1 AND training_id = '" . $tid . "' OR exercise_id='31' AND rep=1 AND training_id = '" . $tid . "' OR exercise_id='30' AND rep=1 AND training_id = '" . $tid . "' OR exercise_id='20' AND rep=1 AND training_id = '" . $tid . "' LIMIT 1";
	if(!$result3 = $db->sql_query($sql3))
	{
		printError("SQL ERROR", mysql_error($sql3));
	}
	$row3 = mysql_fetch_array($result3);
	return $row3['kg'];
	echo "teste";
}

function bestsnatch($tid)
{
	global $db;
	
	//Best squat
	$sql = "SELECT max(kg) as kg FROM " . LIFT_TABLE . " WHERE exercise_id='189' AND rep=1 AND training_id = '" . $tid . "' LIMIT 1";
	if(!$result = $db->sql_query($sql))
	{
		printError("SQL ERROR", mysql_error($sql));
	}
	$row = mysql_fetch_array($result);
	return $row['kg'];
}

function bestcleanandjerk($tid)
{
	global $db;
	
	//Best squat
	$sql = "SELECT max(kg) as kg FROM " . LIFT_TABLE . " WHERE exercise_id='188' AND rep=1 AND training_id = '" . $tid . "' LIMIT 1";
	if(!$result = $db->sql_query($sql))
	{
		printError("SQL ERROR", mysql_error($sql));
	}
	$row = mysql_fetch_array($result);
	return $row['kg'];
}

// Display weight category from 2011 (Powerlifting IPF)
function weightcat($bodyweight, $sex)
{
	if($sex == 'male')
	{
		// -53 class (Only sub-junior)
		if($bodyweight <= 53)
		{
		 return "-53";	
		}
		// -59 class
		elseif($bodyweight >= 53.1 && $bodyweight <= 59)
		{
		 return "-59";	
		}
		// -66 class
		elseif($bodyweight >= 59.1 && $bodyweight <= 66)
		{
		 return "-66";	
		}
		// -74 class
		elseif($bodyweight >= 66.1 && $bodyweight <= 74)
		{
		 return "-74";	
		}
		// -83 class
		elseif($bodyweight >= 74.1 && $bodyweight <= 83)
		{
		 return "-83";	
		}
		// -93 class
		elseif($bodyweight >= 83.1 && $bodyweight <= 93)
		{
		 return "-93";	
		}
		// -105 class
		elseif($bodyweight >= 93.1 && $bodyweight <= 105)
		{
		 return "-105";	
		}
		// -120 class
		elseif($bodyweight >= 105.1 && $bodyweight <= 120)
		{
		 return "-120";	
		}
		// +120 class
		elseif($bodyweight >= 120.1)
		{
		 return "+120";	
		}
	}
	else
	{
		// -43 class (Only sub-junior)
		if($bodyweight <= 43)
		{
		 return "-43";	
		}
		// -47 class
		elseif($bodyweight >= 43.1 && $bodyweight <= 47)
		{
		 return "-47";	
		}
		// -52 class
		elseif($bodyweight >= 47.1 && $bodyweight <= 52)
		{
		 return "-52";	
		}
		// -57 class
		elseif($bodyweight >= 52.1 && $bodyweight <= 57)
		{
		 return "-57";	
		}
		// -63 class
		elseif($bodyweight >= 57.1 && $bodyweight <= 63)
		{
		 return "-63";	
		}
		// -72 class
		elseif($bodyweight >= 63.1 && $bodyweight <= 72)
		{
		 return "-72";	
		}
		// -84 class
		elseif($bodyweight >= 72.1 && $bodyweight <= 84)
		{
		 return "-84";	
		}
		// +84 class
		elseif($bodyweight >= 84.1)
		{
		 return "+84";	
		}
	}
}

// Display weight category before 2011 (Powerlifting IPF)
function weightCatOld($bodyweight, $sex)
{
	
	if($sex == 'male')
	{
		// -52 class
		if($bodyweight <= 52)
		{
		 return "-52";	
		}
		// -56 class
		elseif($bodyweight >= 52.1 && $bodyweight <= 56)
		{
		 return "-56";	
		}
		// -60 class
		elseif($bodyweight >= 56.1 && $bodyweight <= 60)
		{
		 return "-60";	
		}
		// -67.5 class
		elseif($bodyweight >= 60.1 && $bodyweight <= 67.5)
		{
		 return "-67.5";	
		}
		// -75 class
		elseif($bodyweight >= 67.6 && $bodyweight <= 75)
		{
		 return "-75";	
		}
		// -82.5 class
		elseif($bodyweight >= 75.1 && $bodyweight <= 82.5)
		{
		 return "-82.5";	
		}
		// -90 class
		elseif($bodyweight >= 82.6 && $bodyweight <= 90)
		{
		 return "-90";	
		}
		// -100 class
		elseif($bodyweight >= 90.1 && $bodyweight <= 100)
		{
		 return "-100";	
		}
		// -110 class
		elseif($bodyweight >= 100.1 && $bodyweight <= 110)
		{
		 return "-110";	
		}
		// -125 class
		elseif($bodyweight >= 110.1 && $bodyweight <= 125)
		{
		 return "-125";	
		}
		// +125 class
		elseif($bodyweight >= 125.1)
		{
		 return "+125";	
		}
	}
	else
	{
		// -44 class
		if($bodyweight <= 44)
		{
		 return "-44";	
		}
		// -48 class
		elseif($bodyweight >= 44.1 && $bodyweight <= 48)
		{
		 return "-48";	
		}
		// -52 class
		elseif($bodyweight >= 48.1 && $bodyweight <= 52)
		{
		 return "-52";	
		}
		// -56 class
		elseif($bodyweight >= 52.1 && $bodyweight <= 56)
		{
		 return "-56";	
		}
		// -60 class
		elseif($bodyweight >= 56.1 && $bodyweight <= 60)
		{
		 return "-60";	
		}
		// -67.5 class
		elseif($bodyweight >= 60.1 && $bodyweight <= 67.5)
		{
		 return "-67.5";	
		}
		// -75 class
		elseif($bodyweight >= 67.1 && $bodyweight <= 75)
		{
		 return "-75";	
		}
		// -82.5 class
		elseif($bodyweight >= 75.1 && $bodyweight <= 82.5)
		{
		 return "-82.5";	
		}
		// -90 class
		elseif($bodyweight >= 82.6 && $bodyweight <= 90)
		{
		 return "-90";	
		}
		// +90 class
		elseif($bodyweight >= 90.1)
		{
		 return "+90";	
		}
	}
}

// Display age category (Powerlifting IPF)
function getCat($birthday, $sex)
{
	$foo = explode('-',$birthday);
	$ageTime = mktime(0,0,0,$foo[1],$foo[0],$foo[2]);
	$datenow = time();
	
	$YearDiff = date("Y") - $foo[2];
    $MonthDiff = date("m") - $foo[1];
    $DayDiff = date("d") - $foo[0];
     // If the birthday has not occured this year
     if ($DayDiff < 0 || $MonthDiff < 0)
	 
     $YearDiff;

	if($sex == 'male')
	{
		// Sub-junior
		if($YearDiff >= 14 && $YearDiff <= 18)
		{
		 return "sub-junior";	
		}
		// Junior
		elseif($YearDiff >= 19 && $YearDiff <= 23)
		{
		 return "junior";	
		}
		// Senior
		elseif($YearDiff >= 24 && $YearDiff <= 39)
		{
		 return "senior";	
		}
		// Master 1 (o40)
		elseif($YearDiff >= 40 && $YearDiff <= 49)
		{
		 return "master1";	
		}
		// Master 2 (o50)
		elseif($YearDiff >= 50 && $YearDiff <= 59)
		{
		 return "master2";	
		}
		// Masters 3 (o60)
		elseif($YearDiff >= 60 && $YearDiff <= 69)
		{
		 return "master3";	
		}
		// Masters 4 (o70)
		elseif($YearDiff >= 70)
		{
		 return "master4";	
		}
	}
	else
	{
		// Sub-junior
		if($YearDiff >= 14 && $YearDiff <= 18)
		{
		 return "sub-junior";	
		}
		// Junior
		elseif($YearDiff >= 19 && $YearDiff <= 23)
		{
		 return "junior";	
		}
		// Senior
		elseif($YearDiff >= 24 && $YearDiff <= 39)
		{
		 return "senior";	
		}
		// Master 1 (o40)
		elseif($YearDiff >= 40 && $YearDiff <= 49)
		{
		 return "master1";	
		}
		// Master 2 (o50)
		elseif($YearDiff >= 50 && $YearDiff <= 59)
		{
		 return "master2";	
		}
		// Masters 3 (o60)
		elseif($YearDiff >= 60)
		{
		 return "master3";	
		}
	}
}

// Display weight category for Weightligting IWF)
function weightcatw($bodyweight, $sex)
{
	if($sex == 'male')
	{
		// -50 class (Only sub-junior)
		if($bodyweight <= 50)
		{
		 return "-50";	
		}
		// -56 class
		if($bodyweight >= 50.1 && $bodyweight <= 56)
		{
		 return "-56";	
		}
		// -62 class
		elseif($bodyweight >= 56.1 && $bodyweight <= 62)
		{
		 return "-62";	
		}
		// -69 class
		elseif($bodyweight >= 62.1 && $bodyweight <= 69)
		{
		 return "-69";	
		}
		// -77 class
		elseif($bodyweight >= 69.1 && $bodyweight <= 77)
		{
		 return "-77";	
		}
		// -85 class
		elseif($bodyweight >= 77.1 && $bodyweight <= 85)
		{
		 return "-85";	
		}
		// -94 class
		elseif($bodyweight >= 85.1 && $bodyweight <= 94)
		{
		 return "-94";	
		}
		// -105 class
		elseif($bodyweight >= 94.1 && $bodyweight <= 105)
		{
		 return "-105";	
		}
		// +105 class
		elseif($bodyweight >= 105.1)
		{
		 return "+105";	
		}
	}
	else
	{
		// -44 class (Only sub-junior)
		if($bodyweight <= 44)
		{
		 return "-44";	
		}
		// -48 class
		elseif($bodyweight >= 44.1 && $bodyweight <= 48)
		{
		 return "-48";	
		}
		// -53 class
		elseif($bodyweight >= 48.1 && $bodyweight <= 53)
		{
		 return "-53";	
		}
		// -58 class
		elseif($bodyweight >= 53.1 && $bodyweight <= 58)
		{
		 return "-58";	
		}
		// -63 class
		elseif($bodyweight >= 58.1 && $bodyweight <= 63)
		{
		 return "-63";	
		}
		// -69 class
		elseif($bodyweight >= 63.1 && $bodyweight <= 69)
		{
		 return "-69";	
		}
		// -75 class
		elseif($bodyweight >= 69.1 && $bodyweight <= 75)
		{
		 return "-75";	
		}
		// +75 class
		elseif($bodyweight >= 75.1)
		{
		 return "+75";	
		}
	}
}

// Display age category (Weightlifting IWF)
function getCatw($birthday, $sex)
{
	$foo = explode('-',$birthday);
	$ageTime = mktime(0,0,0,$foo[1],$foo[0],$foo[2]);
	$datenow = time();
	
	$YearDiff = date("Y") - $foo[2];
    $MonthDiff = date("m") - $foo[1];
    $DayDiff = date("d") - $foo[0];
     // If the birthday has not occured this year
     if ($DayDiff < 0 || $MonthDiff < 0)
	 
     $YearDiff;

	if($sex == 'male')
	{
		// Sub-junior
		if($YearDiff <= 17)
		{
		 return "sub-junior";	
		}
		// Junior
		elseif($YearDiff >= 18 && $YearDiff <= 20)
		{
		 return "junior";	
		}
		// Senior
		elseif($YearDiff >= 21)
		{
		 return "senior";	
		}
	}
	else
	{
		// Sub-junior
		if($YearDiff <= 17)
		{
		 return "sub-junior";	
		}
		// Junior
		elseif($YearDiff >= 18 && $YearDiff <= 20)
		{
		 return "junior";	
		}
		// Senior
		elseif($YearDiff >= 21)
		{
		 return "senior";	
		}
	}
}

// Display age of a user
function getAge($birthday)
{
		$foo = explode('-',$birthday);
		$ageTime = mktime(0,0,0,$foo[1],$foo[0],$foo[2]);
		$t = time();
		$age = ($ageTime < 0) ? ($t + ($ageTime * -1) ) : ($t - $ageTime);
		$year = 60 * 60 * 24 * 365.25;
		$ageYears = floor($age / $year);
		
		return $ageYears;
}

// Check if a lift is new peronal best
function checkIfNewPr($kglifted, $reps, $ex_id, $training_date, $user_id, $meet)
{
	global $db;
	
	$sql = mysql_query("SELECT
	lifts.kg,
	lifts.rep,
	lifts.exercise_id,
	training.training_id,
	training.meet,
	training.date
	FROM lifts, training
	WHERE training.training_id=lifts.training_id AND training.user_id = ". $user_id ." AND lifts.rep = ". $reps ." AND training.meet = ". $meet ." AND lifts.exercise_id = ". $ex_id ." AND training.date < ". $training_date ." ORDER BY -kg LIMIT 1") or die(mysql_error());
	$num = mysql_num_rows($sql);
	if($num == 1)
	{
	while($row = mysql_fetch_array($sql)) 
		{
			$kg = $row['kg'];
		}
	return $kg;
	}
}

// Get training id from previous peronal best training
function checkIfNewPrTid($kglifted, $reps, $ex_id, $training_date, $user_id, $meet)
{
	global $db;
	
	$sql = mysql_query("SELECT
	lifts.kg,
	lifts.rep,
	lifts.exercise_id,
	training.training_id,
	training.meet,
	training.date
	FROM lifts, training
	WHERE training.training_id=lifts.training_id AND training.user_id = ". $user_id ." AND lifts.rep = ". $reps ." AND training.meet = ". $meet ." AND lifts.exercise_id = ". $ex_id ." AND training.date < ". $training_date ." ORDER BY -kg, training.date LIMIT 1") or die(mysql_error());
	$num = mysql_num_rows($sql);
	if($num == 1)
	{
	while($row = mysql_fetch_array($sql)) 
		{
			$tid = $row['training_id'];
		}
	return $tid;
	}
}

function checkIfNewPrDate($kglifted, $reps, $ex_id, $training_date, $user_id, $meet)
{
	global $db;
	
	$sql = mysql_query("SELECT
	lifts.kg,
	lifts.rep,
	lifts.exercise_id,
	training.training_id,
	training.meet,
	training.date
	FROM lifts, training
	WHERE training.training_id=lifts.training_id AND training.user_id = ". $user_id ." AND lifts.rep = ". $reps . " AND training.meet = ". $meet ." AND lifts.exercise_id = ". $ex_id ." AND training.date < ". $training_date ." ORDER BY -kg, training.date LIMIT 1") or die(mysql_error());
	$num = mysql_num_rows($sql);
	if($num == 1)
	{
	while($row = mysql_fetch_array($sql)) 
		{
			$date = $row['date'];
		}
	return $date;
	}
}

// Get comments from a training
function getCommentTraining($tid)
{
	global $db;
	
	$sql = "SELECT COUNT(comments.post_id) FROM comments WHERE comments.post_id = ". $tid ." AND comments.post_type = 'training' ";
	if(!$result = $db->sql_query($sql))
	{
		printError("SQL ERROR", mysql_error());
	}
	while($row = mysql_fetch_array($result))
		{		
			$nr_of_comments = $row['COUNT(comments.post_id)'];
		}
	return $nr_of_comments;
}

function getVideosTraining($tid)
{
	global $db;
	
	$sql = "SELECT COUNT(lifts.training_id) FROM lifts WHERE lifts.training_id = ". $tid ." AND lifts.url !=  '' ";
	if(!$result = $db->sql_query($sql))
	{
		printError("SQL ERROR", mysql_error());
	}
	while($row = mysql_fetch_array($result))
		{		
			$nr_of_videos = $row['COUNT(lifts.training_id)'];
		}
	return $nr_of_videos;
}

function exercise_list()
{
	global $db;
	$array = array();
	$array2 = array();
	
	$sql = "SELECT * FROM " . EX_CAT_TABLE . " ORDER BY ex_cat_name";
	if(!$result = $db->sql_query($sql))
	{
		printError("SQL ERROR", mysql_error($sql));
	}
	else
	{
		while($row = $db->sql_fetchrow($result))
		{
			$array2 = array();
			
			$sql2 = "SELECT * FROM " . EXERCISE_TABLE . " WHERE ex_cat_id='" . $row['ex_cat_id'] . "' ORDER BY ex_name";
			if(!$result2 = $db->sql_query($sql2))
			{
				printError('SQL_ERROR', mysql_error($sql2));
			}
			else
			{
				while($row2 = $db->sql_fetchrow($result2))
				{
					$array2[] = array(
						'id' =>	$row2['ex_id'],
						'name' => translate($row2['ex_name'])
					);
				}
			}
			
			$array2 = subval_sort($array2,'name');
			
			$array[] = array(
				'id' => 0,
				'name' => translate($row['ex_cat_name']),
				'list' => $array2
			);
		}
	}
	
	$array = subval_sort($array,'name');
	return $array;
}

function getTrainingById($input)
{
	global $db;
	$array = array();
	$lifts = array();
	
	$sql = "SELECT * FROM " . TRAINING_TABLE .
	" WHERE training_id='" . $input . "'";
	
	if(!$result = $db->sql_query($sql))
	{
		printError('SQL_ERROR', mysql_error($sql));
	}
	else
	{
		if($row = $db->sql_fetchrow($result))
		{
			$sql2 = "SELECT * FROM " . LIFT_TABLE .
			" WHERE training_id='" . $input . "' ORDER BY set_id";
			
			if(!$result2 = $db->sql_query($sql2))
			{
				printError('SQL_ERROR', mysql_error($sql2));
			}
			else
			{
				while($row2 = $db->sql_fetchrow($result2))
				{
					$lifts[] = array(
						'id' => $row2['set_id'],
						'exercise_id' => $row2['exercise_id'],
						'kg' => $row2['kg'],
						'rpe' => $row2['rpe'],
						'reps' => $row2['rep'],
						'url' => $row2['url'],
						'type' => $row2['type'],
						'type_nr' => $row2['type_nr']
					);
				}
				$array = array(
					'id' => $row['training_id'],
					'user_id' => $row['user_id'],
					'title' => $row['title'],
					'date' => $row['date'],
					'date_update' => $row['date_update'],
					'comment' => $row['comment'],
					'bodyweight' => $row['bodyweight'],
					'place' => $row['place'],
					'hours' => $row['timespent_hours'],
					'minutes' => $row['timespent_minutes'],
					'disable_comment' => $row['disable_comment'],
					'meet' => $row['meet'],
					'category' => $row['category'],
					'lifts' => $lifts,
					'gym_id'=>$row['gym_id']
				);
			}
		}
	}
	
	return $array;
}

function getNewsById($input)
{
	global $db;
	$array = array();
	$lifts = array();
	
	$sql = "SELECT * FROM " . NEWS_TABLE .
	" WHERE news_id='" . $input . "'";
	
	if(!$result = $db->sql_query($sql))
	{
		printError('SQL_ERROR', mysql_error($sql));
	}
	else
	{
		if($row = $db->sql_fetchrow($result))
		{
				$array = array(
					'id' => $row['news_id'],
					'user_id' => $row['news_user_id'],
					'title' => $row['news_title'],
					'date' => $row['news_date'],
					'date_update' => $row['news_date_update'],
					'comment' => $row['news_message'],
					'disable_comment' => $row['news_disable_comment'],
					'category' => $row['news_category'],
				);
			
		}
	}
	
	return $array;
}

function getTrainingCat($input)
{
	global $db;
	$array = array();
	
	$sql = "SELECT * FROM training_category WHERE training_cat_user_id='" . $input . "' ORDER BY training_cat_name ";
	
	if(!$result = $db->sql_query($sql))
	{
		printError('SQL_ERROR', mysql_error($sql));
	}
	else
	{
		while($row = $db->sql_fetchrow($result))
		{
				$array[] = array(
					'cat_name' => $row['training_cat_name'],
				);
		}
	}
	return $array;
}

function getNewsCat()
{
	global $db;
	$array = array();
	
	$sql = "SELECT * FROM news_category ORDER BY news_cat_name ";
	
	if(!$result = $db->sql_query($sql))
	{
		printError('SQL_ERROR', mysql_error($sql));
	}
	else
	{
		while($row = $db->sql_fetchrow($result))
		{
				$array[] = array(
					'cat_name' => $row['news_cat_name'],
				);
		}
	}
	return $array;
}

function getCountTrainingCat($input, $user_id)
{
	global $db;
	$array = array();
	
	$sql = "SELECT * FROM training WHERE user_id='". $user_id ."' AND category='" . $input . "' ";
	
	if(!$result = $db->sql_query($sql))
	{
		printError('SQL_ERROR', mysql_error($sql));
	}
	$num = mysql_num_rows($result);
	return $num;
}

function getCountNewsCat($input)
{
	global $db;
	$array = array();
	
	$sql = "SELECT * FROM news WHERE news_category='" . $input . "' ";
	
	if(!$result = $db->sql_query($sql))
	{
		printError('SQL_ERROR', mysql_error($sql));
	}
	$num = mysql_num_rows($result);
	return $num;
}

function getCountTrainingUnCat($input, $user_id)
{
	global $db;
	$array = array();
	
	$sql = "SELECT * FROM training WHERE user_id='". $user_id ."' AND category='" . $input . "' ";
	
	if(!$result = $db->sql_query($sql))
	{
		printError('SQL_ERROR', mysql_error($sql));
	}
	$num = mysql_num_rows($result);
	return $num;
}

function getCountNewsUnCat($input)
{
	global $db;
	$array = array();
	
	$sql = "SELECT * FROM news WHERE news_category='" . $input . "' ";
	
	if(!$result = $db->sql_query($sql))
	{
		printError('SQL_ERROR', mysql_error($sql));
	}
	$num = mysql_num_rows($result);
	return $num;
}

function getTrainingList($cmd)
{
	global $db;
	$array = array();
	$lifts = array();
	
	$sql = "SELECT * FROM " . TRAINING_TABLE . $cmd;
	
	if(!$result = $db->sql_query($sql))
	{
		printError('SQL_ERROR', mysql_error($sql));
	}
	else
	{
		while($row = $db->sql_fetchrow($result))
		{
			$lifts = array();
			$sql2 = "SELECT * FROM " . LIFT_TABLE .
			" WHERE training_id='" . $row['training_id'] . "' ORDER BY set_id";
			
			if(!$result2 = $db->sql_query($sql2))
			{
				printError('SQL_ERROR', mysql_error($sql2));
			}
			else
			{
				while($row2 = $db->sql_fetchrow($result2))
				{
					$lifts[] = array(
						'id' => $row2['set_id'],
						'exercise_id' => $row2['exercise_id'],
						'kg' => $row2['kg'],
						'rpe' => $row2['rpe'],
						'reps' => $row2['rep'],
						'url' => $row2['url'],
						'type' => $row2['type'],
						'type_nr' => $row2['type_nr']
					);
				}
				$array[] = array(
					'id' => $row['training_id'],
					'user_id' => $row['user_id'],
					'title' => $row['title'],
					'date' => $row['date'],
					'comment' => $row['comment'],
					'bodyweight' => $row['bodyweight'],
					'place' => $row['place'],
					'hours' => $row['timespent_hours'],
					'minutes' => $row['timespent_minutes'],
					'disable_comment' => $row['disable_comment'],
					'meet' => $row['meet'],
					'category' => $row['category'],
					'lifts' => $lifts,
					'gym_id' => $row['gym_id']
				);
			}
		}
	}
	
	return $array;
}

function countMeets($user_id)
{
	
	global $db;
	
	$sql = "SELECT * FROM " . TRAINING_TABLE . " WHERE user_id=". $user_id ." AND meet=1 OR meet=3";
	
	if(!$result = $db->sql_query($sql))
	{
		printError("SQL ERROR", mysql_error($sql));
	}
	else
	{
		return $db->sql_affectedrows();
	}
	return 0;
}

function countTrainingsU($user_id)
{
	
	global $db;
	
	$sql = "SELECT * FROM " . TRAINING_TABLE . " WHERE user_id=". $user_id ." AND meet=0 ";
	
	if(!$result = $db->sql_query($sql))
	{
		printError("SQL ERROR", mysql_error($sql));
	}
	else
	{
		return $db->sql_affectedrows();
	}
	return 0;
}

function getTrainingListVolume($cmd,$exercises)
{
	global $db;
	$array = array();
	$lifts = array();
	
	$sql = "SELECT * FROM " . TRAINING_TABLE . $cmd;
	
	if(!$result = $db->sql_query($sql))
	{
		printError('SQL_ERROR', mysql_error($sql));
	}
	else
	{
		while($row = $db->sql_fetchrow($result))
		{
			$lifts = array();
			$sql2 = "SELECT * FROM lifts WHERE training_id='". $row['training_id'] ."' AND (". $exercises .")";
			
			if(!$result2 = $db->sql_query($sql2))
			{
				printError('SQL_ERROR', mysql_error($sql2));
			}
			else
			{
				while($row2 = $db->sql_fetchrow($result2))
				{
					$lifts[] = array(
						'id' => $row2['set_id'],
						'exercise_id' => $row2['exercise_id'],
						'kg' => $row2['kg'],
						'rpe' => $row2['rpe'],
						'reps' => $row2['rep'],
						'url' => $row2['url'],
						'type' => $row2['type'],
						'type_nr' => $row2['type_nr']
					);
				}
				$array[] = array(
					'id' => $row['training_id'],
					'user_id' => $row['user_id'],
					'title' => $row['title'],
					'date' => $row['date'],
					'comment' => $row['comment'],
					'bodyweight' => $row['bodyweight'],
					'place' => $row['place'],
					'hours' => $row['timespent_hours'],
					'minutes' => $row['timespent_minutes'],
					'disable_comment' => $row['disable_comment'],
					'meet' => $row['meet'],
					'category' => $row['category'],
					'lifts' => $lifts,
					'gym_id' => $row['gym_id']
				);
			}
		}
	}
	
	return $array;
}

function getNewsList($cmd)
{
	global $db;
	$array = array();
	$lifts = array();
	
	$sql = "SELECT * FROM " . NEWS_TABLE . $cmd;
	
	if(!$result = $db->sql_query($sql))
	{
		printError('SQL_ERROR', mysql_error($sql));
	}
	else
	{
		while($row = $db->sql_fetchrow($result))
		{
			
				$array[] = array(
					'id' => $row['news_id'],
					'user_id' => $row['news_user_id'],
					'title' => $row['news_title'],
					'date' => $row['news_date'],
					'comment' => $row['news_message'],
					'disable_comment' => $row['news_disable_comment'],
					'category' => $row['news_category'],
				);

		}
	}
	
	return $array;
}

function total_kg_lifted($cmd)
{
$time_start = mktime(0, 0, 0, 1, 1, 2000);
$time_end = mktime(23, 59, 59, 12, 31, 2020);

$blogs = getTrainingList(" WHERE user_id='" . $cmd . "' AND date > " . $time_start . " AND date < " . $time_end . " ORDER BY -date");
$results = array();
$month = 0;
$total_weight = 0;
$total_lifts = 0;
foreach($blogs as $k => $v)
	{
		$year = date("Y", $v['date']);
		$month = date("m", $v['date']);
		$day = date("d", $v['date']);
		
		$weight = 0;
		foreach($v['lifts'] as $key => $value)
		{
			$weight += r_nr(calcFromKg($value['kg']));
			$total_weight += r_nr(calcFromKg($value['kg'])) * $value['reps'];
			$total_lifts += $value['reps'];
		}
		if(array_key_exists($year, $results) && array_key_exists($month, $results[$year]) && array_key_exists($day, $results[$year][$month]))
		{
			$results[$year][$month][$day] = $results[$year][$month][$day] + $weight;
		}
		else
		{
			$results[$year][$month][$day] = $weight;
		}
	}
	echo $total_weight;
}

function get_min_max_lifted($cmd, $training_id, $exercise){
/*	global $db;
	
	$sql = "SELECT * FROM ".LIFT_TABLE." WHERE training_id=".$training_id;
	if(!$result = $db->sql_query($sql))
	{
		printError('SQL_ERROR', mysql_error($sql));
	}
	
	$kg_array= array();$sum = 0; $totalREP = 0;
	while($tmp = $db->sql_fetchrow($result)){
		$kg_array[] = $tmp['kg'];
		$sum += $tmp['kg']* $tmp['rep'];
		$totalREP += $tmp['rep'];
	}
	$max = max($kg_array);
	$min = min($kg_array);
	return array('max'=>$max,'min'=>$min,'mean'=>ceil($sum/$totalREP));
**/
	 
	$blogs = getTrainingListVolume(" WHERE user_id='" . $cmd . "' AND training_id = '". $training_id ."' ORDER BY -date",$exercise);
	 
	$kg_array= array(); 
	$total_weight = 0;
	$total_lifts = 0;
	
	foreach($blogs as $k => $v)
	{
		foreach($v['lifts'] as $key => $value)
		{
			$kg_array[] = r_nr(calcFromKg($value['kg']));
			$total_weight += r_nr(calcFromKg($value['kg'])) * $value['reps'];
			$total_lifts += $value['reps'];
		}
	}
	 
	$max = max($kg_array);
	$min = min($kg_array);
	return array('max'=>$max,'min'=>$min,'mean'=>ceil($total_weight/$total_lifts));
}

function total_kg_lifted2($cmd, $training_id, $exercise)
{
	$blogs = getTrainingListVolume(" WHERE user_id='" . $cmd . "' AND training_id = '". $training_id ."' ORDER BY -date",$exercise);
	$results = array();
	$month = 0;
	$total_weight = 0;
	$total_lifts = 0;
	foreach($blogs as $k => $v)
	{
		$year = date("Y", $v['date']);
		$month = date("m", $v['date']);
		$day = date("d", $v['date']);
		
		$weight = 0;
		foreach($v['lifts'] as $key => $value)
		{
			$weight += r_nr(calcFromKg($value['kg']));
			$total_weight += r_nr(calcFromKg($value['kg'])) * $value['reps'];
			$total_lifts += $value['reps'];
		}
		if(array_key_exists($year, $results) && array_key_exists($month, $results[$year]) && array_key_exists($day, $results[$year][$month]))
		{
			$results[$year][$month][$day] = $results[$year][$month][$day] + $weight;
		}
		else
		{
			$results[$year][$month][$day] = $weight;
		}
	}
	return $total_weight;
}

function total_kg_lifted_year($cmd, $training_id, $exercise)
{
$blogs = getTrainingListVolume(" WHERE user_id='" . $cmd . "' AND training_id = '". $training_id ."' ORDER BY -date",$exercise);
$results = array();
$month = 0;
$total_weight = 0;
$total_lifts = 0;
foreach($blogs as $k => $v)
	{
		$year = date("Y", $v['date']);
		
		$weight = 0;
		foreach($v['lifts'] as $key => $value)
		{
			$weight += r_nr(calcFromKg($value['kg']));
			$total_weight += r_nr(calcFromKg($value['kg'])) * $value['reps'];
			$total_lifts += $value['reps'];
		}
		if(array_key_exists($year, $results))
		{
			$results[$year] = $results[$year] + $weight;
		}
		else
		{
			$results[$year] = $weight;
		}
	}
	return $total_weight;
}

function training_archive_list($input)
{
	global $MONTHS;
	$list = array();
	
	$last_month = 0;
	$last_year = 0;
	foreach($input as $key => $value)
	{
		$time = $value['date'];
		
		$year = date('Y', $time);
		$month = date('n', $time) - 1;
		$list[$year][$month][] = array('id' => $value['id'], 'title' => $value['title'], 'comments' => $value['comments'], 'date' => $value['date']);
	}

	return $list;
}

function getBlogComments($cmd)
{
	global $db;
	$array = array();
	
	$sql = "SELECT * FROM comments " . $cmd;
	if(!$result = $db->sql_query($sql))
	{
		printError('SQL_ERROR', mysql_error($sql));
	}
	else
	{
		while($row = $db->sql_fetchrow($result))
		{
			$array[] = array(
				'id' => $row['comment_id'],
				'type' => $row['post_type'],
				'post_id' => $row['post_id'],
				'user_id' => $row['user_id'],
				'date' => $row['comment_date'],
				'date_update' => $row['comment_date_update'],
				'comment' => $row['comment_text'],
				'rating' => $row['comment_rating']
			);
		}
	}
	
	return $array;
}

function getBlogCommentsSort($cmd,$sort)
{
	global $db;
	$array = array();
	
	$sql = "SELECT * FROM comments " . $cmd . " ORDER BY " . $sort . "";
	if(!$result = $db->sql_query($sql))
	{
		printError('SQL_ERROR', mysql_error($sql));
	}
	else
	{
		while($row = $db->sql_fetchrow($result))
		{
			$array[] = array(
				'id' => $row['comment_id'],
				'type' => $row['post_type'],
				'post_id' => $row['post_id'],
				'user_id' => $row['user_id'],
				'date' => $row['comment_date'],
				'date_update' => $row['comment_date_update'],
				'comment' => $row['comment_text'],
				'rating' => $row['comment_rating'],
				'comment_owner' => $row['comment_owner']
			);
		}
	}
	
	return $array;
}

//hungdd
function get_3_latest_comments($cmd,$sort){
	global $db;
	$array = array();
	$sort = 'comment_date DESC';
	 
	$sql = "SELECT * FROM comments " . $cmd . " ORDER BY " . $sort . " LIMIT 2";
	if(!$result = $db->sql_query($sql))
	{
		printError('SQL_ERROR', mysql_error($sql));
	}
	else
	{
		while($row = $db->sql_fetchrow($result))
		{
			$array[] = array(
				'id' => $row['comment_id'],
				'type' => $row['post_type'],
				'post_id' => $row['post_id'],
				'user_id' => $row['user_id'],
				'date' => $row['comment_date'],
				'date_update' => $row['comment_date_update'],
				'comment' => $row['comment_text'],
				'rating' => $row['comment_rating'],
				'comment_owner' => $row['comment_owner'],
				'comment_id'	=> $row['comment_id'],
				'owner_id'		=> $row['user_id']
			);
		}
	}
	
	return array_reverse($array, true);
}

function getNewsComments($cmd)
{
	global $db;
	$array = array();
	
	$sql = "SELECT * FROM comments " . $cmd;
	if(!$result = $db->sql_query($sql))
	{
		printError('SQL_ERROR', mysql_error($sql));
	}
	else
	{
		while($row = $db->sql_fetchrow($result))
		{
			$array[] = array(
				'id' => $row['comment_id'],
				'type' => $row['post_type'],
				'post_id' => $row['post_id'],
				'user_id' => $row['user_id'],
				'date' => $row['comment_date'],
				'date_update' => $row['comment_date_update'],
				'comment' => $row['comment_text'],
				'rating' => $row['comment_rating']
			);
		}
	}
	
	return $array;
}

function getNewsCommentsSort($cmd,$sort)
{
	global $db;
	$array = array();
	
	$sql = "SELECT * FROM comments " . $cmd . " ORDER BY " . $sort . "";
	if(!$result = $db->sql_query($sql))
	{
		printError('SQL_ERROR', mysql_error($sql));
	}
	else
	{
		while($row = $db->sql_fetchrow($result))
		{
			$array[] = array(
				'id' => $row['comment_id'],
				'type' => $row['post_type'],
				'post_id' => $row['post_id'],
				'user_id' => $row['user_id'],
				'date' => $row['comment_date'],
				'date_update' => $row['comment_date_update'],
				'comment' => $row['comment_text'],
				'rating' => $row['comment_rating']
			);
		}
	}
	
	return $array;
}

function getShowBlogComments($userid)
{
	global $db;
	$array = array();
	
	$sql = "SELECT * FROM comments WHERE post_type = 'training' AND comment_owner = " . $userid . " ORDER BY comment_date DESC LIMIT 5";
	if(!$result = $db->sql_query($sql))
	{
		printError('SQL_ERROR', mysql_error($sql));
	}
	else
	{
		while($row = $db->sql_fetchrow($result))
		{
			$array[] = array(
				'id' => $row['comment_id'],
				'type' => $row['post_type'],
				'post_id' => $row['post_id'],
				'user_id' => $row['user_id'],
				'date' => $row['comment_date'],
				'date_update' => $row['comment_date_update'],
				'comment' => $row['comment_text'],
				'rating' => $row['comment_rating']
			);
		}
	}
	
	return $array;
}

function getShowNewsComments()
{
	global $db;
	$array = array();
	
	$sql = "SELECT * FROM comments, news WHERE post_id = news_id AND post_type='news' ORDER BY comment_date DESC LIMIT 10";
	if(!$result = $db->sql_query($sql))
	{
		printError('SQL_ERROR', mysql_error($sql));
	}
	else
	{
		while($row = $db->sql_fetchrow($result))
		{
			$array[] = array(
				'id' => $row['comment_id'],
				'type' => $row['post_type'],
				'post_id' => $row['post_id'],
				'user_id' => $row['user_id'],
				'date' => $row['comment_date'],
				'date_update' => $row['comment_date_update'],
				'comment' => $row['comment_text'],
				'rating' => $row['comment_rating']
			);
		}
	}
	
	return $array;
}

function getAllComments($nr)
{
	global $db;
	$array = array();
	
	$sql = "SELECT comments.comment_id, comments.post_type, comments.post_id, comments.user_id, comments.comment_date, comments.comment_date_update, comments.comment_text, comments.comment_rating FROM comments ORDER BY comment_date DESC LIMIT " . $nr ." ";
	if(!$result = $db->sql_query($sql))
	{
		printError('SQL_ERROR', mysql_error($sql));
	}
	else
	{
		while($row = $db->sql_fetchrow($result))
		{
			$array[] = array(
				'id' => $row['comment_id'],
				'type' => $row['post_type'],
				'post_id' => $row['post_id'],
				'post_type' => $row['post_type'],
				'user_id' => $row['user_id'],
				'date' => $row['comment_date'],
				'date_update' => $row['comment_date_update'],
				'comment' => $row['comment_text'],
				'rating' => $row['comment_rating']
			);
		}
	}
	
	return $array;
}

function getAllNews($nr)
{
	global $db;
	$array = array();
	
	$sql = "SELECT * FROM news ORDER BY news_date DESC LIMIT " . $nr ." ";
	if(!$result = $db->sql_query($sql))
	{
		printError('SQL_ERROR', mysql_error($sql));
	}
	else
	{
		while($row = $db->sql_fetchrow($result))
		{
			$array[] = array(
				'id' => $row['news_id'],
				'user_id' => $row['news_user_id'],
				'title' => $row['news_title'],
				'message' => $row['news_message'],
				'date' => $row['news_date']
			);
		}
	}
	
	return $array;
}

function getTrainingTitle($id)
{
	global $db;
	
	$sql = "SELECT title FROM training WHERE training_id = ". $id ." ";
	if(!$result = $db->sql_query($sql))
	{
		printError('SQL_ERROR', mysql_error($sql));
	}
	else
	{
		//while($row = $db->sql_fetchrow($result))
		//{
			$row = $db->sql_fetchrow($result);
			$title = $row['title'];
		//}
		
	}
	return $title;
}

function getPreviouesTrainingId($userid, $current_tid, $date)
{
	global $db;
	
	$sql = "SELECT training_id, date FROM training WHERE user_id = ". $userid ." AND date < ". $date ." ORDER BY date DESC LIMIT 1";
	if(!$result = $db->sql_query($sql))
	{
		printError('SQL_ERROR', mysql_error($sql));
	}
	else
	{
		while($row = $db->sql_fetchrow($result))
		{
			$tid = $row['training_id'];
		}
	}
	if(!empty($tid))
	{
	return $tid;
	}
}

function checkPreviouesSet($tid, $current_set_id, $type_nr, $exercise)
{
	global $db;
	
	$sql = "SELECT type FROM lifts WHERE exercise_id = ". $exercise ." AND training_id = ". $tid ." AND set_id < ". $current_set_id ." AND type_nr = ". $type_nr ." ORDER BY set_id DESC LIMIT 1";
	if(!$result = $db->sql_query($sql))
	{
		printError('SQL_ERROR', mysql_error($sql));
	}
	else
	{
		while($row = $db->sql_fetchrow($result))
		{
			$type = $row['type'];
		}
	}
	if(!empty($type))
	{
	return $type;
	}
}

function checkPreviouesSet2($tid, $current_set_id, $type_nr, $exercise)
{
	global $db;
	
	$sql = "SELECT type FROM lifts WHERE exercise_id = ". $exercise ." AND training_id = ". $tid ." AND set_id < ". $current_set_id ." AND type_nr = ". $type_nr ." ORDER BY set_id DESC LIMIT 1,1";
	if(!$result = $db->sql_query($sql))
	{
		printError('SQL_ERROR', mysql_error($sql));
	}
	else
	{
		while($row = $db->sql_fetchrow($result))
		{
			$type = $row['type'];
		}
	}
	if(!empty($type))
	{
	return $type;
	}
}

function checkPreviouesSet3($tid, $current_set_id, $type_nr, $exercise)
{
	global $db;
	
	$sql = "SELECT type FROM lifts WHERE exercise_id = ". $exercise ." AND training_id = ". $tid ." AND set_id < ". $current_set_id ." AND type_nr = ". $type_nr ." ORDER BY set_id DESC LIMIT 2,1";
	if(!$result = $db->sql_query($sql))
	{
		printError('SQL_ERROR', mysql_error($sql));
	}
	else
	{
		while($row = $db->sql_fetchrow($result))
		{
			$type = $row['type'];
		}
	}
	if(!empty($type))
	{
	return $type;
	}
}

function checkPreviouesSet4($tid, $current_set_id, $type_nr, $exercise)
{
	global $db;
	
	$sql = "SELECT type FROM lifts WHERE exercise_id = ". $exercise ." AND training_id = ". $tid ." AND set_id < ". $current_set_id ." AND type_nr = ". $type_nr ." ORDER BY set_id DESC LIMIT 3,1";
	if(!$result = $db->sql_query($sql))
	{
		printError('SQL_ERROR', mysql_error($sql));
	}
	else
	{
		while($row = $db->sql_fetchrow($result))
		{
			$type = $row['type'];
		}
	}
	if(!empty($type))
	{
	return $type;
	}
}

function checkPreviouesSet5($tid, $current_set_id, $type_nr, $exercise)
{
	global $db;
	
	$sql = "SELECT type FROM lifts WHERE exercise_id = ". $exercise ." AND training_id = ". $tid ." AND set_id < ". $current_set_id ." AND type_nr = ". $type_nr ." ORDER BY set_id DESC LIMIT 4,1";
	if(!$result = $db->sql_query($sql))
	{
		printError('SQL_ERROR', mysql_error($sql));
	}
	else
	{
		while($row = $db->sql_fetchrow($result))
		{
			$type = $row['type'];
		}
	}
	if(!empty($type))
	{
	return $type;
	}
}

function getNewerTrainingId($userid, $current_tid, $date)
{
	global $db;
	
	$sql = "SELECT training_id, date FROM training WHERE user_id = ". $userid ."  AND date > ". $date ."  ORDER BY date ASC LIMIT 1";
	if(!$result = $db->sql_query($sql))
	{
		printError('SQL_ERROR', mysql_error($sql));
	}
	else
	{
		while($row = $db->sql_fetchrow($result))
		{
			$tid = $row['training_id'];
		}
		
	}
	if(!empty($tid))
	{
	return $tid;
	}
}

function getNewsTitle($id)
{
	global $db;
	
	$sql = "SELECT news_title FROM news WHERE news_id = ". $id ." ";
	if(!$result = $db->sql_query($sql))
	{
		printError('SQL_ERROR', mysql_error($sql));
	}
	else
	{
		while($row = $db->sql_fetchrow($result))
		{
			$title = $row['news_title'];
		}
		
	}
	return $title;
}

function deleteCommentById($input)
{
	$sql="DELETE FROM `treningsblogg`.`comments` WHERE `comments`.`comment_id` = " . $input .  "";
	if(!$result = $db->sql_query($sql))
	{
		printError('SQL_ERROR', mysql_error($sql));
	}
	
}

function formatComment($input)
{
	global $CONFIG;

	// TAG: [quote=ID]TEXT[/quote]
	// ID = id to the comment
	// TEXT = the text concerning the comment (is replaced by original comment)

	$replace = array('/(\[quote name=)(.+)( date=)(.+)(\])(.+)(\[\/quote\])/', '/(\[quote name=)(.+)(\])(.+)(\[\/quote\])/', '/(\[quote\])(.+)(\[\/quote\])/');
	$replacements = array ("<br /><span class=\"quote_title\">". translate('quoted_from') ." \\2 - [date=\\4]</span><blockquote>\\6</blockquote>", "<br /><span class=\"quote_title\">". translate('quoted_from') ." \\2</span><blockquote>\\4</blockquote>", "<blockquote>\\2</blockquote>");
	$input = preg_replace($replace, $replacements, $input);
	$posStart = 0;
	$posEnd = 0;
	$dateCounter = substr_count($input, "[date=");
	$loopCounter = 0;
	while($dateCounter > 0)
	{
		if($dateCounter == 0)
		{
			$posStart = strpos($input, "[date=");
			$posEnd = strpos($input, "]", $posStart);
		}
		else
		{
			$posStart = strpos($input, "[date=", $posStart);
			$posEnd = strpos($input, "]", $posStart);
		}
		$dateSrc = (int)substr($input, ($posStart + 6), ($posEnd - $posStart - 6));
		$date = formatDate($dateSrc, $CONFIG['date_format_long']);
		$input = substr_replace($input, $date, $posStart, ($posEnd-$posStart + 1));
		
		$loopCounter++;
		$dateCounter--;
	}
	return $input;
}

function getExercisename($id)
{
	global $db;
	
	$sql = "SELECT ex_name FROM " . EXERCISE_TABLE .
	" WHERE ex_id='" . $id . "'";
	
	if(!$result = $db->sql_query($sql))
	{
		printError('SQL_ERROR', mysql_error($sql));
	}
	else
	{
		if($row = $db->sql_fetchrow($result))
		{
			return $row['ex_name'];
		}
	}
	return $id;
}

function post_stat_image($array)
{
	global $w_metric;
	$output = "";
	foreach($array as $k => $v)
	{
		$output .= r_nr(calcFromKg($v)) . ",";
	}
	
	$output = substr($output, 0, strlen($output) - 1);
	
	return "<img src=\"image.php?values=" . $output . "&metric=" . $w_metric . "&size=200\" alt=\"[Graph]\" />";
}
function getSettings($setting)
{
	global $db;
	
	$sql = "SELECT ". $setting ." FROM settings";
	if(!$result = $db->sql_query($sql))
	{
		printError('SQL_ERROR', mysql_error($sql));
	}
	else
	{
		while($row = $db->sql_fetchrow($result))
		{
			$value = $row[$setting];		
		}
		
	}
	return $value;
}

function getTrainingIdFromUser($userid)
{
	global $db;
	
	$sql = "SELECT training_id FROM training WHERE user_id = ". $userid ." ";
	if(!$result = $db->sql_query($sql))
	{
		printError('SQL_ERROR', mysql_error($sql));
	}
	else
	{
		while($row = $db->sql_fetchrow($result))
		{
			$value = " training_id=" .$row['training_id'] . " ";		
		}
		
	}
	return $value;
}

function countNewBlogsToday()
{
	global $db;
	
	$time_now = time();
	$day = date('d', $time_now);
	$month = date('m', $time_now);
	$year = date('Y', $time_now);
	$date = mktime(date('H', 00), date('i', 00), date('s', 00), $month, $day, $year);
	
	$sql = "SELECT * FROM " . TRAINING_TABLE . " WHERE date > ". $date ." ";
	
	if(!$result = $db->sql_query($sql))
	{
		printError("SQL ERROR", mysql_error($sql));
	}
	else
	{
		return $db->sql_affectedrows();
	}
	return 0;
}

function countNewMembersToday()
{
	global $db;
	
	$time_now = time();
	$day = date('d', $time_now);
	$month = date('m', $time_now);
	$year = date('Y', $time_now);
	$date = mktime(date('H', 00), date('i', 00), date('s', 00), $month, $day, $year);
	
	$sql = "SELECT * FROM " . USERS_TABLE . " WHERE user_joined > ". $date ." ";
	
	if(!$result = $db->sql_query($sql))
	{
		printError("SQL ERROR", mysql_error($sql));
	}
	else
	{
		return $db->sql_affectedrows();
	}
	return 0;
}

function countNewCommentsToday()
{
	global $db;
	
	$time_now = time();
	$day = date('d', $time_now);
	$month = date('m', $time_now);
	$year = date('Y', $time_now);
	$date = mktime(date('H', 00), date('i', 00), date('s', 00), $month, $day, $year);
	
	$sql = "SELECT * FROM " . COMMENTS_TABLE . " WHERE comment_date > ". $date ." ";
	
	if(!$result = $db->sql_query($sql))
	{
		printError("SQL ERROR", mysql_error($sql));
	}
	else
	{
		return $db->sql_affectedrows();
	}
	return 0;
}

function countNewVideosToday()
{
	global $db;
	
	$time_now = time();
	$day = date('d', $time_now);
	$month = date('m', $time_now);
	$year = date('Y', $time_now);
	$date = mktime(date('H', 00), date('i', 00), date('s', 00), $month, $day, $year);
	
	$sql = "SELECT * FROM lifts, training WHERE lifts.url != '' AND training.training_id=lifts.training_id AND training.date > ". $date ." ";
	
	if(!$result = $db->sql_query($sql))
	{
		printError("SQL ERROR", mysql_error($sql));
	}
	else
	{
		return $db->sql_affectedrows();
	}
	return 0;
}

function checkWeightChangeOnSets($t_id,$set_id,$ex_id)
{
	global $db;
	
	$sql = "SELECT kg FROM lifts WHERE training_id = ". $t_id ." AND set_id < ". $set_id ." AND exercise_id = ". $ex_id." ORDER BY set_id DESC LIMIT 1";
	if(!$result = $db->sql_query($sql))
	{
		printError("SQL ERROR", mysql_error($sql));
	}
	
	$num = mysql_num_rows($result);
	
	if($num == 1)
	{
		while($row = mysql_fetch_array($result)) 
			{
				$weight = $row['kg'];
			}
			
		return $weight;
	}
}

function checkIfWeightChangeOnSetsIsFirstSet($t_id,$ex_id)
{
	global $db;
	
	$sql = "SELECT set_id FROM lifts WHERE training_id = ". $t_id ." AND exercise_id = ". $ex_id." ORDER BY set_id ASC LIMIT 1";
	if(!$result = $db->sql_query($sql))
	{
		printError("SQL ERROR", mysql_error($sql));
	}
	
	$num = mysql_num_rows($result);
	
	if($num == 1)
	{
		while($row = mysql_fetch_array($result)) 
			{
				$set_id = $row['set_id'];
			}
			
		return $set_id;
	}
}

//hungdd
function UI_get_3_latest_comments($user_id, $training_id){
	global $CONFIG;
	$gavatar = "";
	$MY_PROFILE = new User('id',$_SESSION['user_id']);
	$USER = new User('id',$user_id);
	$all_comments = getBlogCommentsSort(" WHERE post_type='training' AND post_id='" . $training_id . "' ",$USER->getSortComments());
	$three_latest_comments = get_3_latest_comments(" WHERE post_type='training' AND post_id='" . $training_id . "' ",$USER->getSortComments());
	
	if(empty($all_comments)){return '';}
	
	$dateformat = $CONFIG['date_format'];
	$dateformat_long = $CONFIG['date_format_long'];
	
	$response = "";
	
	if(count($all_comments) > 2){
		$response .= "<li class='comment'>";
		$response .= "<div class='info'>";
		$response .= "<a href='javascript:void(0);' onclick='javascript:open_comments2($training_id,$user_id);' >".translate('view_all_comments')."</a>";
		$response .= "</div><div class='fixed'></div>";
		$response .= "<div class='content'>&nbsp;</div>";
		$response .= "<div class='fixed'></div></li>";	
	}
	
	foreach($three_latest_comments as $k=>$v){
		$COMMENT = $v;
		$U_PROFILE = new User('id', $COMMENT['user_id']);
		$comment_id = $COMMENT['id'];
		$comment_head = translate('comment_from') . " " . $U_PROFILE->getFirstname() . " " . formatDate($COMMENT['date'], $CONFIG['date_format_long']) . "\n";

		$comment_text = ($COMMENT['comment']);
		
		if($U_PROFILE->getAvatarpath() != "")
		{
			$profile_pic_path = $CONFIG['user_data_path'] . $U_PROFILE->getId() . "/thumbs_" . $U_PROFILE->getAvatarpath();
			if(file_exists($profile_pic_path))
			{
				$gavatar= "<a href='index.php?action=profile&amp;id=" . $U_PROFILE->getId() . "'>
				<img style='background: url(" . $profile_pic_path . ") no-repeat 50%; height: 30px; width: 30px;' src=\"" . $profile_pic_path . "\" alt=\"" . translate('profile_picture') . "\" /></a>\n";
			}
		}
		else
		{
			if($U_PROFILE->getGender() == "female")
			{
				$gavatar= "<a href='index.php?action=profile&amp;id=" . $U_PROFILE->getId() . "'>
				<img src=\"" . $CONFIG['user_data_path'] . "profile_female.gif\" height='30' width='30' alt=\"" . translate('profile_picture') . "\" /></a>\n";
			}
			else
			{
				$gavatar= "<a href='index.php?action=profile&amp;id=" . $U_PROFILE->getId() . "'>
				<img src=\"" . $CONFIG['user_data_path'] . "profile_male.gif\" height='30' width='30' alt=\"" . translate('profile_picture') . "\" /></a>\n";
			}
		}	//
		$like_comment = "<a href='javascript:void(0);' onclick=\"return open_who_like_comment(". $training_id .",". $COMMENT['comment_id'] .");\"><img src='./img/thumb_up.png' alt='". translate('like') ."' /></a>
						<span class='like_comment' rel='". $COMMENT['comment_id'] ."'>". count_numberOfPersons_like_comment($COMMENT['user_id'], $training_id, $COMMENT['comment_id']);
		if(is_like_comment($COMMENT['user_id'],$_SESSION['user_id'], $training_id, $COMMENT['comment_id'])){
			$like_comment .= " <a href='javascript:void(0);' onclick=\"like_unlike_comment('unlike_comment',".$_SESSION['user_id'].",". $COMMENT['owner_id'].",". $training_id.",".$COMMENT['comment_id'] .");\" >". translate('unlike')."</a>";
		}else{
			$like_comment .= " <a href='javascript:void(0);' onclick=\"like_unlike_comment('like_comment',".$_SESSION['user_id'].",". $COMMENT['owner_id'].",". $training_id.",".$COMMENT['comment_id'] .");\" >". translate('like')."</a>";
		}
		$like_comment .= "</span>";
		$like_comment .= "&nbsp;".ui_aj_follow_this_user($COMMENT['user_id'], $COMMENT['user_id']);
		
		$response .= "<li class='comment'>";
		$response .= "<div class='info'>";
		$response .= "<div class='date2'>";
		$response .= "<div style='float: left; clear: right; padding-right: 3px;'>".$gavatar."</div>";;
		$response .= "<a href='index.php?action=profile&amp;id=".$COMMENT['user_id']."' >"; 
		$response .= "".htmlentities($U_PROFILE->getFirstname())." ". htmlentities($U_PROFILE->getLastname())." (" . ucf(getCountryName(htmlentities($U_PROFILE->getCountry()))) . ") " .
					  "</a>";
		
		$response .= " ".translate('the')." ";			 
		$response .= formatDate($COMMENT['date'], $dateformat_long) . "";        
		if($COMMENT['date_update'] != 0)
		{
			 $response .=  " (" . ucf(translate('updated')) . " " . translate('for2') . " " . getHowLongAgo($COMMENT['date_update']). ")"; 
		}
		$response .= "<br/>".$like_comment;
		$response .= "</div>" ;          
		$response .= "<div class='fixed'></div>";
		$response .= "<div id='comment_$comment_id' class='content'>";
		$response .= nl2br(formatComment(htmlentities($COMMENT['comment']))); 
		$response .= "</div></div><div class='fixed'></div></li>";			
	}
	
	if($MY_PROFILE->getAvatarpath() != "")
	{
		$profile_pic_path = $CONFIG['user_data_path'] . $MY_PROFILE->getId() . "/thumbs_" . $MY_PROFILE->getAvatarpath();
		if(file_exists($profile_pic_path))
		{
			$gavatar= "<a href='index.php?action=profile&amp;id=" . $MY_PROFILE->getId() . "'>
			<img style='background: url(" . $profile_pic_path . ") no-repeat 50%; height: 30px; width: 30px;' src=\"" . $profile_pic_path . "\" alt=\"" . translate('profile_picture') . "\" /></a>\n";
		}
	}
	else
	{
		if($MY_PROFILE->getGender() == "female")
		{
			$gavatar= "<a href='index.php?action=profile&amp;id=" . $MY_PROFILE->getId() . "'>
			<img src=\"" . $CONFIG['user_data_path'] . "profile_female.gif\" height='30' width='30' alt=\"" . translate('profile_picture') . "\" /></a>\n";
		}
		else
		{
			$gavatar= "<a href='index.php?action=profile&amp;id=" . $MY_PROFILE->getId() . "'>
			<img src=\"" . $CONFIG['user_data_path'] . "profile_male.gif\" height='30' width='30' alt=\"" . translate('profile_picture') . "\" /></a>\n";
		}
	}

	$response .= "<li class='comment'>";
	$response .= "<div class='info'>";
	$response .= $gavatar;
	$response .= "<input type='text' id='comment_new' name='comment_new' size='50' maxlength='250' 
					onkeypress='comment(this,".$_SESSION['user_id'].",$training_id,event);' />";
	$response .= "</div><div class='fixed'></div>";
	$response .= "<div class='content'>&nbsp;</div>";
	$response .= "<div class='fixed'></div></li>";	
	
	return $response;
}

function getVideoInfor($url) {
	// get video ID from $_GET 
	if (!isset($url)) {
	  return 'Please enter a YouTube video URL.';
	} else {
		$vid = stripslashes($url);
		$string = $vid;
		$url = parse_url($string);
		if(isset($url['query'])){
			parse_str($url['query']);
		}else{
			$v = substr($url['path'], 1,strlen($string) - 1);
			if(strstr($v, "user")){
				$v = substr($url['fragment'], 8, strlen($url['fragment']));
			}
		}
	}
	if(!isset($v)){
		return null;
	}	
	// set video data feed URL
	$feedURL = 'http://gdata.youtube.com/feeds/api/videos/'. $v;

	
	//Since allow_url_fopens is off  use curl to get
	//the xml document from youtube. ;)
	//Added by DNI Web Design, June 11, 2010
	$ch = curl_init();    // initialize curl handle
	curl_setopt($ch, CURLOPT_URL,$feedURL); // set url to post to
	curl_setopt($ch, CURLOPT_RETURNTRANSFER,1); // return into a variable
	curl_setopt($ch, CURLOPT_TIMEOUT, 4); // times out after 4s
	
	$result = curl_exec($ch); // run the whole process*/

	// read feed into SimpleXML object
	
	$old_track = ini_set('track_errors', '1');

	if (!@$entry = simplexml_load_string($result)) {
		ini_set('track_errors', $old_track);
		return null;
	}

	//$entry = simplexml_load_string($result);
	if(!$entry){
		return null;
	}
	try {
		//print_r($entry);
		// parse video entry
		//$video = $this->parseVideoEntry($entry);
		$videoInfor = array();
		//These variables include the video information
		$videoInfor["title"] = stripslashes(iconv('UTF-8', 'ISO-8859-15//TRANSLIT', $entry->title));
		$videoInfor["published"] = stripslashes(iconv('UTF-8', 'ISO-8859-15//TRANSLIT', $entry->published));
		$videoInfor["content"] = stripslashes(iconv('UTF-8', 'ISO-8859-15//TRANSLIT', $entry->content));
		$media = $entry->children('http://search.yahoo.com/mrss/');
		  // get video thumbnail
		$attrs = $media->group->thumbnail[2]->attributes();
		$videoInfor["thumbnail"] = stripslashes($attrs['url']);
			
		$videoInfor["author"] = stripslashes($entry->author->name);
		$videoInfor["author_uri"] = stripslashes($entry->author->uri);
		
		// get <yt:duration> node for video length
		$yt = $media->children('http://gdata.youtube.com/schemas/2007');
		$attrs = $yt->duration->attributes();
		$videoInfor["seconds"] = $attrs['seconds']; 
		
		$yt = $entry->children('http://gdata.youtube.com/schemas/2007');
		$attrs = $yt->statistics->attributes();
		$videoInfor['viewCount'] = $attrs['viewCount'];
		 
		$videoInfor["key"] = $v;
		return $videoInfor;
	}catch (Exception $e) {
		return null;
	}
}
function secondsToTime($seconds)
{
    // extract hours
    $hours = floor($seconds / (60 * 60));
 
    // extract minutes
    $divisor_for_minutes = $seconds % (60 * 60);
    $minutes = floor($divisor_for_minutes / 60);
 
    // extract the remaining seconds
    $divisor_for_seconds = $divisor_for_minutes % 60;
    $seconds = ceil($divisor_for_seconds);
 
    // return the final string
	if($hours == 0){
		$stringTime = $minutes.':'.$seconds;
	}else{
		$stringTime = $hours.':'.$minutes.':'.$seconds;
	}
    return $stringTime;
}

function dayToDateString ($day)
  {
    list($year,$month,$day) = explode("-",$day);
    $year_diff  = date("Y") - $year;
    $month_diff = date("m") - $month;
    $day_diff   = date("d") - $day;
	
	if($year_diff == 0){
		$monthTemp = date("m") - $month;
		return $monthTemp." ".translate('months')." ".translate('Ago');
	}
	
    if ($month_diff < 0) $year_diff--;
    elseif (($month_diff==0) && ($day_diff < 0)) $year_diff--;
	if($year_diff > 0){
		return $year_diff." ".translate('years')." ".translate('Ago');
	}else{
		$monthTemp = 12 - $month + date("m");
		return $monthTemp." ".translate('months')." ".translate('Ago');
	}
  }
?>